import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public class GsonUtils {

    public static final boolean SERIALIZE_NULLS = true;
    public static final boolean NOT_SERIALIZE_NULLS = false;

    private static final Gson GSON = createGson(SERIALIZE_NULLS);
    private static final Gson GSON_NO_NULLS = createGson(NOT_SERIALIZE_NULLS);

    /**
     * 创建Gson对象
     *
     * @return Gson对象
     */
    public static Gson createGson() {
        return createGson(SERIALIZE_NULLS);
    }

    /**
     * 创建Gson对象
     *
     * @param serializeNulls 值为null的属性是否会被序列化
     * @return Gson对象
     */
    public static Gson createGson(final boolean serializeNulls) {
        final GsonBuilder builder = new GsonBuilder();
        if (serializeNulls) {
            builder.serializeNulls();
        }
        return builder.create();
    }

    /**
     * 解析json格式的文件流
     *
     * @param reader
     * @param classType
     * @param <T>
     * @return
     */
    public static <T> T fromJson(FileReader reader, Class<T> classType) {
        JsonReader jsonReader = null;
        try {
            jsonReader = new JsonReader(reader);
            return GSON.fromJson(jsonReader, classType);
        } catch (Exception e) {
            return null;
        } finally {
            try {
                reader.close();
                jsonReader.close();
            }catch (IOException e){
                e.printStackTrace();
            }

        }

    }

    /**
     * 解析json格式的文件流
     *
     * @param file
     * @param classType
     * @param <T>
     * @return
     */
    public static <T> T fromJson(File file, Class<T> classType) {
        JsonReader jsonReader = null;
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(file);
            jsonReader = new JsonReader(fileReader);
            return GSON.fromJson(jsonReader, classType);
        } catch (Exception e) {
            return null;
        } finally {
            try {
                fileReader.close();
                jsonReader.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
